<template>
  <div class="mt-4">
    <el-input
      width="100px"
      v-model.trim="searchinput"
      placeholder="请输入查询用户名
        "
      class="input-with-select"
      @keydown.enter="getUser"
    >
      <template #append>
        <el-button :icon="Search" @click="getUser" />
      </template>
    </el-input>
    <el-button type="primary" @click="openUser">添加用户</el-button>
    <user-dialog ref="child" @getFromDate="getFromDate"></user-dialog>
  </div>

  <el-table
    :data="
      filterTableData.slice(
        (currentPage - 1) * pageSize,
        currentPage * pageSize
      )
    "
    style="width: 100%"
  >
    <el-table-column type="index" width="50" label="#" />
    <el-table-column label="姓名" prop="username" />
    <el-table-column label="邮箱" prop="email" />
    <el-table-column label="电话" prop="mobile" />
    <el-table-column label="角色" prop="role_name" />
    <el-table-column>
      <template #header> 状态 </template>
      <template #default="scope">
        <el-switch v-model="scope.row.mg_state" @click="open2(scope.row)" />
      </template>
    </el-table-column>

    <el-table-column align="right" label="操作">
      <!-- <template #header>
      <el-input v-model="search" size="small" placeholder="Type to search" />
       
      </template> -->

      <template #default="scope">
        <!-- 编辑按钮 -->
        <el-button
          type="primary"
          :icon="Edit"
          circle
          @click="handleEdit(scope.$index, scope.row)"
        />
        <edit-dialog ref="edit" @getEdit="handleEdit"></edit-dialog>

        <!-- 权限分配按钮 -->
        <el-button
          type="warning"
          :icon="Setting"
          circle
          @click="handlePower(scope.$index, scope.row)"
        />
        <PowerDialog ref="Power" @getPower="handlePower"></PowerDialog>

        <!-- 删除 -->
        <el-button
          type="danger"
          :icon="Delete"
          circle
          @click="handleDelete(scope.$index, scope.row)"
        />
        <DeleteDialog
          ref="deleteChildren"
          @deleteUser="deleteUser"
        ></DeleteDialog>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->

  <div class="demo-pagination-block">
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[1, 2, 5, 10]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filterTableData.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { Delete, Edit, Setting, Search } from "@element-plus/icons-vue";
import { computed, ref, reactive, watch } from "vue";
// 删除弹窗
import DeleteDialog from "./components/DeleteDialog.vue";
// 编辑弹窗
import editDialog from "./components/EditDialog.vue";
// 添加弹窗
import userDialog from "./components/userDialog.vue";
// 权限弹窗
import PowerDialog from "./components/PowerDialog.vue";

import { ElMessage } from "element-plus";

import { getUserList, DeleteUser, setUsersState } from "@/api/Users";
import { getRoleList } from "@/api/role";
import { useStore } from "vuex";

// 使用vuex数据
const store = useStore();
// 改变状态提示
const open2 = async (row: { id: number; mg_state: boolean }) => {
  // console.log(row.id, "修改状态");
  let res = await setUsersState(row.id, row.mg_state);
  // console.log(res, "修改状态");
  ElMessage({
    message: "修改了状态",
    type: "success",
  });
};

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
};

// 表单信息
interface User {
  username: string;
  email: string;
  mobile: string;
  role_name: string;
  mg_state: boolean | string;
  id?: number;
  rid?: number;
}

// 获取子组件方法
const child = ref();
const edit = ref();
const Power = ref();
const deleteChildren = ref();
// 打开添加弹窗
const openUser = () => {
  child.value.openDialog();
};
// 接收添加弹窗的数据
const getFromDate = (form: {
  username: string;
  email: string;
  mobile: string;
  passwor: string;
  id?: number; //用户id
  rid?: number; //用户角色 ID
  mg_state: boolean | string;
}) => {
  console.log(form);
  const { username, email, mobile, id, rid, mg_state } = form;
  tableData.push({
    username,
    email,
    mobile,
    role_name: "超级管理员",
    mg_state,
    id,
    rid,
  });
};

const search = ref("");
const filterTableData = computed(() =>
  tableData.filter(
    (data) =>
      !search.value ||
      data.username.toLowerCase().includes(search.value.toLowerCase())
  )
);
// 编辑操作
// 接收编辑表格数据
const handleEdit = (index: number, row: User) => {
  // console.log(index);
  if (row.role_name) {
    // console.log(index);
    // 打开弹窗
    edit.value.openDialog(index, row);
    // console.log(row);
  } else {
    // console.log(row);
    tableData[index].email = row.email;
    tableData[index].mobile = row.mobile;
  }
};

// 分配权限
const handlePower = async (index: number, row: User) => {
  // console.log(index, row, "rowwwwwwwwwwwww");
  if (row.mobile) {
    // console.log(index, row);
    let res = await getRoleList();
    // console.log(res, "分配角色信息123321");
    store.dispatch("user/SET_USERID", res.data.data);
    Power.value.openDialog(index, row);
    Power.value.getOption(row.id);
  } else {
    // console.log(row, "回来的row");
    // console.log(store.state.user.userID);
    for (let i = 0; i < store.state.user.userID.length; i++) {
      if (store.state.user.userID[i].id === row.id) {
        tableData[index].role_name = store.state.user.userID[i].roleName;
      }
    }
  }
};

// 删除信息
const handleDelete = (index: number, row: User) => {
  deleteChildren.value.open(index, row);
  // console.log(index, row.id);
  // let res = await DeleteUser(row.id);
  // console.log(res, res.data.meta.msg);
  // tableData.splice(index, 1);
};
const deleteUser = (index: number) => {
  tableData.splice(index, 1);
};

const tableData: User[] = reactive([]);

// 搜索框
const searchinput = ref("");
// 获取用户信息
const getUser = async () => {
  tableData.splice(0);
  let res = await getUserList({
    pagenum: currentPage.value, // 当前页码
    pagesize: pageSize.value, // 每页显示条数
  });
  // 模糊搜索
  if (searchinput.value === "") {
    tableData.push(...res.data.data.users);
  } else {
    for (let i = 0; i < res.data.data.users.length; i++) {
      if (res.data.data.users[i].username.includes(searchinput.value)) {
        tableData.push(res.data.data.users[i]);
      }
    }
  }
  console.log(tableData);
};
// 开局触发一次
watch(
  () => searchinput.value,
  () => {
    if (searchinput.value === "") getUser();
  },
  { immediate: true }
);
</script>
<style lang="scss" scoped>
.mt-4 {
  width: 400px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  .el-button {
    height: 38px;
  }
}
.el-input-group {
  width: 300px;
  height: 40px;
}

// 分页
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
<style>
.el-table .el-table__cell.is-right {
  text-align: left;
}
.el-table__inner-wrapper::before {
  z-index: 0;
}

/* 修改状态的提示弹窗 */
.el-message--success {
  border: 1px dashed rgb(7, 218, 60);
  width: 325px;
}
</style>
